/**
 * 分部数据
 * wangmei
 */
import React, { Component } from 'react';
import { Tabs, Row, Table, Col, Button, Input, DatePicker, Form, Select, message, Checkbox, Spin  } from 'antd';
import EchartPage from '../report/EchartPage';
import { getClassifiesAll } from '../../../Server/SystemManger';
import * as Utils from '../../../common/utils';
import moment from 'moment';
import {REQUEST_SUCCESS,REQUEST_UNAUTHORIZED} from '../../../common/const';
require('../sysinfo//sysinfo.css');
require('../../systemManager/customer.css');

const { MonthPicker, RangePicker } = DatePicker;
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const dateFormat = 'YYYY-MM-DD';
const monthFormat = 'YYYY-MM';
const Option = Select.Option;
const currentDate = new Date();

class CommonDayPart extends Component{
    constructor(props) {
        super(props);
        const { sysCompany } = this.props;
        this.state = {
            partNameData: [], //分部名数据
            startIp: sysCompany.startIp, //分部管理起始ip
            endIp: sysCompany.endIp, //分部管理结束ip
            endOpen: false,
        };
    }

    componentWillMount() {
        const { sysCompany } = this.props;
        this.getPartName();
        this.props.getChartData({queryDate: currentDate, startMonth: currentDate, endMonth: currentDate}, sysCompany.startIp, sysCompany.endIp);
    }

    //分部查询方法
    handleBranchSubmit = (e) =>{
        const { startIp, endIp, value } = this.state;
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if(!err){
                let startValue = values.startIp?values.startIp : startIp;
                let endValue = values.endIp?values.endIp : endIp;
                this.props.getChartData(values, startValue, endValue);
            }
        });
    }

    //分部名选择事件
    partNameSelect = (value, option) =>{
        this.props.form.setFieldsValue({startIp: '', endIp: ''});
        this.setState({
            startIp: option.props.startIp,
            endIp: option.props.endIp
        })
    }

    //获取分部名数据
    getPartName = () =>{
        getClassifiesAll().then(res => {
            if(res && res.code == REQUEST_SUCCESS){
                const data = res.data
                this.setState({
                    partNameData: data,
                });
            }else{
                res.code !== REQUEST_UNAUTHORIZED && message.error(res.msg);
            }
        });
    }

    //校验起始ip
    checkStartIP = (rule, value, callback) =>{
        let { startIp, endIp } = this.state;
        const { sysCompany, form } = this.props;
        if(value==''||value==undefined){
            if(sysCompany.id==1){
                callback();
                return ;
            }else{
                callback('请输入起始IP地址！');
                return ;
            }
        }
        if(!Utils.checkIP(value)){
            callback('请输入正确地IP地址！');
            return ;
        }else if(!Utils.checkIPValue(value, startIp, endIp)){
            callback('请输入分部范围内的IP地址！');
            return ;
        }else if(!Utils.checkIPCount(form.getFieldValue("startIp"),form.getFieldValue("endIp"))){
            callback('起始IP不能大于结束IP');
            return ;
        }
        if(form.getFieldValue('endIp') && form.getFieldError('endIp')){
            form.validateFields(['endIp'],{ force: true });
        }
        callback();
    }

    //校验结束ip
    checkEndIP = (rule, value, callback) =>{
        let { startIp, endIp } = this.state;
        const { sysCompany, form } = this.props;
        if(value==''||value==undefined){
            if(sysCompany.id==1){
                callback();
                return ;
            }else{
                callback('请输入结束IP地址！');
                return ;
            }
        }
        if(!Utils.checkIP(value)){
            callback('请输入正确地IP地址！');
            return ;
        }else if(!Utils.checkIPValue(value, startIp, endIp)){
            callback('请输入分部范围内的IP地址！');
            return ;
        }else if(!Utils.checkIPCount(form.getFieldValue("startIp"),form.getFieldValue("endIp"))){
            callback('结束IP不能小于起始IP');
            return ;
        }
        if(form.getFieldValue('startIp') && form.getFieldError('startIp')){
            form.validateFields(['startIp'],{ force: true });
        }
        callback();
    }

    //导出方法
    outPutFunc = () =>{
        const { _headers, _data, fileName, yData } = this.props;
        const maxData = Math.max(...yData);
        Utils.outPutExcel(_headers, _data, fileName, maxData);
    }

    //开始时间禁填
    disabledStartDate = (startValue) => {
        const endValue = this.props.form.getFieldValue('endMonth');
        if (!startValue || !endValue) {
            return startValue.valueOf() > Date.now();
        }
        return startValue.valueOf() > Date.now()&&startValue.valueOf() >= endValue.valueOf();
    }

    //禁止时间
    disabledDate = (current) =>{
        // can not select days before today and today
        return current && current.valueOf() > Date.now();
    }

    //结束时间禁填
    disabledEndDate = (endValue) => {
        const startValue = this.props.form.getFieldValue('startMonth');
        if (!endValue || !startValue) {
            return endValue.valueOf() > Date.now();
        }
        return endValue.valueOf() < startValue.valueOf() || endValue.valueOf() > Date.now();
    }

    //开始月份弹出日历和关闭日历的回调
    handleStartOpenChange = (open) => {
        if (!open) {
            this.setState({ endOpen: true });
        }
    }
    
    //结束月份弹出日历和关闭日历的回调
    handleEndOpenChange = (open) => {
        this.setState({ endOpen: open });
    }

    validateSn = (rule, value, callback) =>{
        if(Utils.CheckSnFunc(value)){
            callback('序列号存在非法字符,请重新输入');
            return ;
        }
        callback();
        return;
    }

    validateVersion = (rule, value, callback) =>{
        if(Utils.CheckSnFunc(value)){
            callback('版本号存在非法字符,请重新输入');
            return ;
        }
        callback();
        return;
    }

    render(){           
        const { sysCompany, state, columns, data, loading, xData, yData, xName, yName, title, 
            legendData, formatter, flag, checkState, checkData, checkChange, columns1 } = this.props;
        const { getFieldDecorator } = this.props.form;
        const { partNameData, endOpen } = this.state;
        const partNameOptions = partNameData.map(d => <Option value={d.id} endIp={d.endIp} startIp={d.startIp} >{d.name}</Option>);
        let msoState = yName.indexOf("MSO")<0
        let unInstallState = yName.indexOf("卸载")<0

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 7 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 17 },
            },
        };

        const timeLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 11 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 13 },
            },
        };

        return(
            <div style={{height: '100%'}}>
                <Spin spinning={loading} >
                <Form onSubmit={this.handleBranchSubmit}>
                    {msoState&&<Row>
                        <Col span={6}>
                            <FormItem
                                {...formItemLayout}
                                label="通道号"
                            >
                                {getFieldDecorator('monthDistNum')(
                                    <Input maxLength={255}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <FormItem
                                {...formItemLayout}
                                label="版本号"
                            >
                                {getFieldDecorator('monthVersion',{
                                    rules: [{
                                        validator: this.validateVersion
                                    }],
                                })(
                                    <Input maxLength={250}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <FormItem
                                {...formItemLayout}
                                label="序列号"
                            >
                                {getFieldDecorator('monthSn',{
                                    rules: [{
                                        validator: this.validateSn
                                    }],
                                })(
                                    <Input maxLength={250}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <Col span={12}>
                                <FormItem
                                    {...formItemLayout}
                                    label="IP"
                                >
                                    {getFieldDecorator('startIp',{
                                        rules: [{
                                            validator: this.checkStartIP 
                                        }],
                                        initialValue: state?"":sysCompany.startIp
                                    })(
                                        <Input maxLength={255}/>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={2} style={{ textAlign: 'center'}}>
                                <FormItem>
                                    <label>-</label>
                                </FormItem>
                            </Col>
                            <Col span={10}>
                                <FormItem
                                    wrapperCol = {{
                                        xs: { span: 24 },
                                        sm: { span: 20 },
                                    }}
                                >
                                    {getFieldDecorator('endIp',{
                                        rules: [{
                                            validator: this.checkEndIP 
                                        }],
                                        initialValue: state?"":sysCompany.endIp
                                    })(
                                        <Input maxLength={255}/>
                                    )}
                                </FormItem>
                            </Col>
                        </Col>
                    </Row>}
                    <Row>
                        {state&&<Col span={6}>
                            <FormItem
                                {...formItemLayout}
                                label="分部名"
                            >
                                {getFieldDecorator('partName',{
                                    initialValue: sysCompany.id
                                })(
                                    <Select
                                        showSearch
                                        style={{ width: '100%' }}
                                        optionFilterProp="children"
                                        onSelect={this.partNameSelect}
                                        filterOption={true}
                                    >
                                        {partNameOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>}
                        {!msoState&&<Col span={6}>
                            <Col span={12}>
                                <FormItem
                                    {...formItemLayout}
                                    label="IP"
                                >
                                    {getFieldDecorator('startIp',{
                                        rules: [{
                                            validator: this.checkStartIP 
                                        }],
                                        initialValue: state?"":sysCompany.startIp
                                    })(
                                        <Input maxLength={255}/>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={2} style={{ textAlign: 'center'}}>
                                <FormItem>
                                    <label>-</label>
                                </FormItem>
                            </Col>
                            <Col span={10}>
                                <FormItem
                                    wrapperCol = {{
                                        xs: { span: 24 },
                                        sm: { span: 20 },
                                    }}
                                >
                                    {getFieldDecorator('endIp',{
                                        rules: [{
                                            validator: this.checkEndIP 
                                        }],
                                        initialValue: state?"":sysCompany.endIp
                                    })(
                                        <Input maxLength={255}/>
                                    )}
                                </FormItem>
                            </Col>
                        </Col>}
                        {flag=='month'?<Col span={6} style={{marginLeft: '0.18%'}}>
                            <Col span={15}>
                                <FormItem
                                    {...timeLayout}
                                    label="时间"
                                >
                                    {getFieldDecorator('startMonth',{
                                        initialValue: moment(currentDate, monthFormat)
                                    })(
                                        <MonthPicker 
                                            allowClear={false}
                                            disabledDate={this.disabledStartDate}
                                            placeholder="开始月份" 
                                            onOpenChange={this.handleStartOpenChange}
                                        />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={1} style={{ textAlign: 'center'}}>
                                <FormItem>
                                    <label>~</label>
                                </FormItem>
                            </Col>
                            <Col span={8}>
                                <FormItem
                                    wrapperCol = {{
                                        xs: { span: 24 },
                                        sm: { span: 24},
                                    }}
                                >
                                    {getFieldDecorator('endMonth',{
                                        initialValue: moment(currentDate, monthFormat)
                                    })(
                                        <MonthPicker 
                                            style={{ width: '99%'}}
                                            allowClear={false}
                                            disabledDate={this.disabledEndDate}
                                            placeholder="结束月份" 
                                            open={endOpen}
                                            onOpenChange={this.handleEndOpenChange}
                                        />
                                    )}
                                </FormItem>
                            </Col>
                        </Col>:<Col span={6}>
                            <FormItem
                                {...formItemLayout}
                                label="时间"
                            >
                                {getFieldDecorator('queryMonth', {
                                    initialValue: moment( currentDate, monthFormat)
                                })(
                                    <MonthPicker  
                                        disabledDate={this.disabledDate}
                                        style={{ width: '100%'}}
                                        format={monthFormat}
                                        allowClear = {false}
                                    />
                                )}
                            </FormItem>
                        </Col>}
                        {(flag=='month'&&msoState&&unInstallState)&&<Col span={2} className='check-margin'>
                            <FormItem>
                                <Checkbox onChange={checkChange}>多月排重</Checkbox>
                            </FormItem>
                        </Col>}
                        <Col span={2} className={(flag=='month'&&msoState&&unInstallState)?"check-button-margin":'count-button-margin'} style={{zIndex: 1}}>
                            <FormItem>
                                <Button type="primary" htmlType="submit">查询</Button>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
                <Row>
                    <Col span={19} style={{ paddingTop: 30 }}>
                        <EchartPage 
                            title={title}
                            xName={xName}
                            yName={yName}
                            xData={xData} 
                            yData={yData}
                            legendData={legendData}
                            formatter={formatter}
                        />
                    </Col>
                    <Col span={5} style={{ paddingRight: '1.7%'}}>
                        <Row type="flex" justify="end" className='output-button'>
                            <Button size='large' style={{ fontSize: 14}} onClick={()=>this.outPutFunc()}>导出列表</Button>
                        </Row>
                        <Table
                            className='output-table'
                            dataSource={checkState?checkData:data}
                            loading={loading}
                            columns={checkState?columns1:columns}
                            scroll={{ y: 600 }}
                            pagination={false}
                        />
                    </Col>
                </Row>
                </Spin>
            </div>
        )
    }
}

export default Form.create()(CommonDayPart)